/**
 * Created with CLion.
 * Description: 
 * User: loong
 * Date: 2020-11-11
 * Time: 22:25
 */

#include "MyDialog.h"

MyDialog::MyDialog()
{
    InitUi();
    InitEvent();
}

MyDialog::~MyDialog()
{

}

void MyDialog::InitUi()
{
    QGridLayout * main_layout = new QGridLayout(this);
    btn1 = new QPushButton("work1");
    btn2 = new QPushButton("work2");

    label1 = new QLabel("label1");
    label2 = new QLabel("label2");

    main_layout->addWidget(btn1,0,0 );
    main_layout->addWidget(btn2,0,1 );
    main_layout->addWidget(label1,1,0 ,Qt::AlignCenter);
    main_layout->addWidget(label2,1,1 ,Qt::AlignCenter);
}

void MyDialog::InitEvent()
{
    connect(btn1,&QPushButton::clicked,this,&MyDialog::MainThread);
}

void MyDialog::MainThread()
{
    first_worker_ = new FirstWorker();
    QThread * thread = new  QThread();
    first_worker_->moveToThread(thread);

    connect(thread,&QThread::started,first_worker_,&FirstWorker::SlotWork1);
    connect(first_worker_,&FirstWorker::SignalNum,this, &MyDialog::SlotLabel1);
    connect(first_worker_,&FirstWorker::SignalFinish,thread,&QThread::quit);
    connect(thread,&QThread::finished,this,&MyDialog::SlotFinished);
    connect(thread,&QThread::finished,first_worker_,&FirstWorker::deleteLater);
    connect(thread,&QThread::finished,thread,&QThread::deleteLater);

    thread->start();
}

void MyDialog::SlotLabel1(const int _num)
{
    label1->clear();
    label1->setText(QString::number(_num));
}

void MyDialog::SlotLabel2(const int _num)
{
    label2->clear();
    label2->setText(QString::number(_num));
}

void MyDialog::SlotFinished()
{
    second_worker_ = new SecondWorker();
    QThread * thread = new  QThread();
    second_worker_->moveToThread(thread);

    connect(thread,&QThread::started,second_worker_,&SecondWorker::SlotWork2);
    connect(second_worker_,&SecondWorker::SignalNum,this, &MyDialog::SlotLabel2);
    connect(second_worker_,&SecondWorker::SignalFinish,thread,&QThread::quit);
    connect(thread,&QThread::finished,second_worker_,&SecondWorker::deleteLater);
    connect(thread,&QThread::finished,thread,&QThread::deleteLater);

    thread->start();
}

SecondWorker::SecondWorker()
{

}

SecondWorker::~SecondWorker()
{
    qDebug()<< "SecondWorker deletee";
}

void SecondWorker::SlotWork2()
{
    static int i = 6;
    qDebug()<< QThread::currentThreadId();
    while (i++< 20){
        QThread::sleep(1);
        emit SignalNum(i);
        if(i == 16){
            emit SignalFinish();
            break;
        }
    }
}


FirstWorker::FirstWorker()
{

}

FirstWorker::~FirstWorker()
{
    qDebug()<< "FirstWorker deletee";
}

void FirstWorker::SlotWork1()
{
    static int i = 0;
    qDebug()<< QThread::currentThreadId();
    while (i++ < 10){
        QThread::sleep(1);
        emit SignalNum(i);
        if(i == 6){
            emit SignalFinish();
            break;
        }
    }
}
